/*
     File: MainViewController.m
 Abstract: The application's main view controller (front page).
  Version: 1.0
 CopyLeft: Michael Artuerhof (c) 2009

 */
#import "MainViewController.h"

#import "railwaysController.h"
#import "ModalViewController.h"
#import "undergroundController.h"
#import "busController.h"

#import "Constants.h"	// contains the dictionary keys
#import "dataBase.h"

#include "structForDB.h"


@implementation MainViewController

@synthesize menuList, myTableView, myModalViewController;
@synthesize navController;
@synthesize underground;
@synthesize viewContr;

static NSArray *pageNames = nil;

- (void)dealloc
{    
	[myTableView release];
	[menuList release];
	if (self.myModalViewController != nil)
		[myModalViewController release];
	
	[super dealloc];
}
-(void) releaseAllUnneededElements: (NSString*) strName
{
	//printf("I should release all unneeded elements! _nLoad: %d; _nCur: %d\n", 
	//				_nLoadedDirection, _nCurRailway);
	for(int i=0; i<[self.menuList count]; i++)
    {	
		// do not release current railway:
		if(_nLoadedDirection==i)
			continue;
		railwaysController* contr=[[self.menuList objectAtIndex:i] objectForKey:kViewControllerKey];
		if(contr!=nil && ![contr unneededStuffWasReleased] && 
			![strName isEqualToString:contr.databaseName]){
			[contr releaseAllStuff];
			//[contr release];
			NSMutableDictionary *rowData = [self.menuList objectAtIndex: i];
			[rowData setValue: nil forKey:kViewControllerKey];
		}
    }		
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
	//printf("Should select view controller!\n");
	int nTab=[self.tabBarController.viewControllers indexOfObject: viewController];
	//printf("Should select view controller! tabBar: %d Last: %d\n", nTab, _nTabBar);
	// select the last one tab bar action:
	if(nTab==_nTabBar)
		return FALSE;
	
	switch (_nTabBar) {
		case 0:	 		
			[busy startAnimating];	
			break;
		case 1:
			[_buses showLoadingIndicator];
			break;
		case 2:
			[(undergroundController*)underground showLoadingIndicator];
			break;
		default:
			[busy startAnimating];
			break;
	}
	
	if(!_bHaveToLoadAnotherDir){		
		[NSTimer scheduledTimerWithTimeInterval: 0.1f
				 target:self selector:@selector(loadAnotherController) userInfo:nil repeats: NO];	
		_nTabBar=nTab;//[self.tabBarController.viewControllers indexOfObject: viewController];
		//_bHaveToLoadAnotherDir=true;		
		return FALSE;
	}
	else{		
		_nTabBar=nTab;
		_bHaveToLoadAnotherDir=false;
		
		return TRUE;
	}
}

-(void) loadAnotherController
{
	//printf("Load new controller!\n");
	_bHaveToLoadAnotherDir=true;
	[self.tabBarController setSelectedIndex: _nTabBar];
}

- (void)viewDidLoad
{	
	// staff for localized buses title...
	[_buses setTitle: NSLocalizedString(@"busesTitle", @"")];
	
	_nLoadedDirection=-1;
	_nCurRailway=-1;
	self.menuList = [NSMutableArray array];
	
	if(!_directions)
		_directions = [[NSArray alloc] initWithObjects:@"Belorussia", @"Gorky", 
					   @"Kazan", @"Kiew", @"Kolcev", @"Kursk", @"Lenin", 
					   @"Pavel", @"Riga", @"Savel", @"Yaroslavl", nil];	
	
	// initialize storage (for the user selection):
	[self initStorage];
	// read all remembered data from it:
	[self readStorage];
	
	// We will lazily create our view controllers as the user requests them (at a later time),
	// but for now we will encase each title an explanation text into a NSDictionary and add it to a mutable array.
	// This dictionary will be used by our table view data source to populate the text in each cell.
	//
	// When it comes time to create the corresponding view controller we will replace each NSDictionary.
	//
	// If you want to add more pages, simply call "addObject" on "menuList"
	// with an additional NSDictionary.  Note we use NSLocalizedString to load a localized version of its title.
    if (!pageNames)
	{
		pageNames = [[NSArray alloc] initWithObjects:@"Page1", @"Page2", @"Page3", @"Page4", @"Page5",
					 @"Page6", @"Page7", @"Page8", @"Page9", @"Page10", @"Page11", nil];
    }
	
		
    for (NSString *pageName in pageNames)
	{
		[self.menuList addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
                             NSLocalizedString([pageName stringByAppendingString:@"Title"], @""), kTitleKey,
                             NSLocalizedString([pageName stringByAppendingString:@"Explain"], @""), kDetailKey,
                             nil]];
	}
	
    // Create a final modal view controller
	UIButton* modalViewButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
	[modalViewButton addTarget:self action:@selector(modalViewAction:) forControlEvents:UIControlEventTouchUpInside];
	UIBarButtonItem *modalBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:modalViewButton];
	self.navigationItem.leftBarButtonItem = modalBarButtonItem;
	[modalBarButtonItem release];
	
	[self.myTableView reloadData];
	[self setTitle:NSLocalizedString(@"railwaysTitle", @"")];
	
	// get subscribed to the termination notification:	
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillTerminate:)
                                                 name:UIApplicationWillTerminateNotification 
                                               object:app];
	
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	if([[defaults objectForKey: kQuerShow] isEqualToString:@"quer"]){
		_bShowQuer=true;
	}
		
	// added for saving resources, show how many direction views, we've loaded into memory...
    nCurAmountOfDirections = 0;
	underground.master = self;
	_nTabBar=_nCurrentTab;
	[self.tabBarController setSelectedIndex:_nCurrentTab];	
}

- (void)viewDidUnload
{
	self.myTableView = nil;
	self.menuList = nil;
}

- (void)viewWillDisappear:(BOOL)animated{	
	// doesn't work!
	//printf("View will disapper (main controller)!\n");
	[busy startAnimating];	
	
	if(!_bLoadADirection){
		_nLoadedDirection=-1;
		_nCurRailway=-1;
		
		_bOtherViewWasShown=true;
		
		nCurAmountOfDirections=0;	 
		[self releaseAllUnneededElements:@"All Of them!"];			 
    }		
}

- (void)applicationWillTerminate:(NSNotification *)notification {
	//printf("Writting data to file.\n");	
	// write all info we need to disk	
	[self writeStorage];	
}

-(void) checkSizes
{
	// resize myself... dancing with TabBar again... 
	// if I do not make, user cannot select some directions:
	myTableView.frame=CGRectMake(0, 0, kScreenWidth, kScreenHeight-114);	
}

- (void)viewWillAppear:(BOOL)animated
{
	_nCurRailway=-1;
	[busy stopAnimating];
	_bHaveToLoadAnotherDir=false;	

	[NSTimer scheduledTimerWithTimeInterval: 0.1
									 target:self selector:@selector(checkSizes) 
								   userInfo:nil repeats: NO];
	_bLoadADirection=false;
	
	[self.myTableView deselectRowAtIndexPath:self.myTableView.indexPathForSelectedRow animated:NO];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
	printf("Load another direction!\n");
	//[self.tabBarController
}

#pragma mark -
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // Change the navigation bar style, also make the status bar match with it
	switch (buttonIndex)
	{
		case 0:
		{
			[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
			self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
			break;
		}
		case 1:
		{
			[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackOpaque;
			self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
			break;
		}
		case 2:
		{
			[UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleBlackTranslucent;
			self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
			break;
		}
	}
}


#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return menuList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{	
	static NSString *kCellIdentifier = @"cellID";
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
	if (!cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCellIdentifier] autorelease];
        
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        cell.textLabel.backgroundColor = [UIColor clearColor];
		cell.textLabel.opaque = NO;
		cell.textLabel.textColor = [UIColor blackColor];
		cell.textLabel.highlightedTextColor = [UIColor whiteColor];
		cell.textLabel.font = [UIFont boldSystemFontOfSize:18];
		
		cell.detailTextLabel.backgroundColor = [UIColor clearColor];
		cell.detailTextLabel.opaque = NO;
		cell.detailTextLabel.textColor = [UIColor grayColor];
		cell.detailTextLabel.highlightedTextColor = [UIColor whiteColor];
		cell.detailTextLabel.font = [UIFont systemFontOfSize:14];
    }
    
	// get the view controller's info dictionary based on the indexPath's row	
    NSDictionary *dataDictionary = [menuList objectAtIndex:indexPath.row];
    cell.textLabel.text = [dataDictionary valueForKey:kTitleKey];
    
	cell.detailTextLabel.text = @"";
	
	return cell;
}


#pragma mark -
#pragma mark UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{   
	if(_nCurRailway==indexPath.row)
		return;
	[busy startAnimating];	
	_nCurRailway=indexPath.row;
	
	[NSTimer scheduledTimerWithTimeInterval: 0.1
									 target:self selector:@selector(loadDirection) 
								   userInfo:nil repeats: NO];
}

-(void) loadDirection
{
	NSMutableDictionary *rowData = [self.menuList objectAtIndex: _nCurRailway];	
	
	UIViewController *targetViewController = [rowData objectForKey:kViewControllerKey];	
	if(!targetViewController)
	{
		targetViewController = [[railwaysController alloc] 
								initWithNibName:@"RailwaysInterface" bundle:nil];        
		((railwaysController*)targetViewController).name=(NSString*)[rowData valueForKey:kTitleKey];
		//[_directions objectAtIndex: indexPath.row];
		((railwaysController*)targetViewController).databaseName=(NSString*)[_directions objectAtIndex: _nCurRailway];
		[((railwaysController*)targetViewController) setMaster:self];
		((railwaysController*)targetViewController).tabBarController=self.tabBarController;
		((railwaysController*)targetViewController).navController=self.navController;	

		[((railwaysController*)targetViewController) setQuer: _bShowQuer];
		
		// I think system hangs on while it's grabbing on this... WRONG:)
		[rowData setValue:targetViewController forKey:kViewControllerKey];
		[targetViewController release];		
	}
	/*
	if([(railwaysController*)targetViewController unneededStuffWasReleased])
		[(railwaysController*)targetViewController loadAllNeededStuff];
	 */	
	nCurAmountOfDirections++;	 
	
	if(nCurAmountOfDirections>=kMaximumDirections)
	{		
	    nCurAmountOfDirections=1;
		//printf("I'd like to remove resources from main view controller!\n");
		for(int i=0; i<[self.menuList count]; i++)
	    {		
			if(i==_nCurRailway)
				continue;
			railwaysController* contr=[[self.menuList objectAtIndex:i] objectForKey:kViewControllerKey];
			if(contr!=nil && ![contr unneededStuffWasReleased]){
				[contr releaseAllStuff];
				nCurAmountOfDirections--;
				break;
			}				
	    }			
	}	
	
	_bLoadADirection=true;	
	// for not releasing current direction:
	_nLoadedDirection=_nCurRailway;
    [self.navigationController pushViewController:targetViewController animated:YES];	
}

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
	//printf("We should pop item now!");
	return TRUE;
}

#pragma mark -
#pragma mark API

- (IBAction)styleAction:(id)sender
{
	
	UIActionSheet *styleAlert = [[UIActionSheet alloc] initWithTitle:@"Choose a UIBarStyle:"
												delegate:self cancelButtonTitle:@"Cancel"
												destructiveButtonTitle:nil
												otherButtonTitles:	@"Default",
																	@"BlackOpaque",
																	@"BlackTranslucent",
																	nil,
																	nil];	
	// use the same style as the nav bar
	[styleAlert showInView:self.view];
	[styleAlert release];
}

- (IBAction)modalViewAction:(id)sender
{
    if (self.myModalViewController == nil)
        self.myModalViewController = 
		[[[ModalViewController alloc] initWithNibName: @"ModalViewController" bundle:nil] autorelease];

	[self.navigationController presentModalViewController:self.myModalViewController animated:YES];
}
@end

